<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Session;

use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UCenterController extends Controller{   // 分析师用户中心
    public function __construct() {
//        DB::connection()->enableQueryLog();
//        DB::table('waihui_order'); 
//        $queries = DB::getQueryLog(); 
    }
    
    public function myusercenter(Request $request){  //个人中心
        $sessionData = $request->session()->get('eai');
        
        //自己看自己的时候需要判读是否登录  客户未登录也能查看分析师个人中心
        if($request->get('type')){   // 分析师/客户 自己看自己的个人中心
            $type = htmlspecialchars(trim($request->get('type')));
            if($type != 'user' || !$sessionData){
                if(isMobile()){
                    return redirect('mlogin');
                }else{
                    return redirect('login');
                }
            }
                   

            //判断用户的喊单量，如果>=30单，那么他的用户中心是分析师的，如果小于30的，那么他的用户中心是客户的

            $handanliang = DB::table('waihui_member')->select('alltraid')->where('id','=',$sessionData['id'])->first();
            if(!$handanliang){
                if(isMobile()){
                    return redirect('mlogin');
                }else{
                    return redirect('login');
                }
            }
            if($handanliang->alltraid < 30){
                return redirect('kehuhome?type=user&id='.$sessionData['id']);
            }else{
                return redirect('analysthome?type=user&id='.$sessionData['id']);
            }
            
        }else{  //客户看分析师的个人中心
            $uid = intval($request->get('id'));
            if(!$uid){
                return redirect('bdlists');
            }else{
                if($sessionData && $sessionData['id'] == $uid){
                    return redirect('analysthome?type=user&id='.$sessionData['id']);
                }else{
                    return redirect('analysthome?id='.$uid);
                }
            }
        }
    }
    
    public function kehuCenter(Request $request){  //客户的用户中心
//        $tiyan = getenv('tiyan'); //申请体验账户
        $id = intval(trim($request->get('id')));
        if(!$id || $id == 0){
            return redirect('bdlists');
        }
        //判断策略量,并且判断当前用户是否存在
        $handanliang = DB::table('waihui_member')->select('alltraid')->where('id','=',$id)->first();
        $sessionData = $request->session()->get('eai');
        if($request->get('type')){   //客户自己看自己的个人中心
            $type = htmlspecialchars(trim($request->get('type')));
            if($type != 'user' || !$sessionData){
                if(isMobile()){
                    return redirect('mlogin');
                }else{
                    return redirect('login');
                }
            }else if($sessionData['id'] != $id){
                if(!$handanliang){
                    if(isMobile()){
                        return redirect('mlogin');
                    }else{
                        return redirect('login');
                    }
                }else if($handanliang->alltraid >= 30){ 
                    return redirect('analysthome?id='.$id);
                }else{
                   return redirect('kehuhome?id='.$id);
                }
                
            }
        }else{
            if($sessionData['id'] == $id){
                if(!$handanliang){
                    if(isMobile()){
                        return redirect('mlogin');
                    }else{
                        return redirect('login');
                    }
                }else if($handanliang->alltraid >= 30){ 
                    return redirect('analysthome?type=user&id='.$id);
                }else{
                   return redirect('kehuhome?type=user&id='.$id);
                }
            }
        } 
        
        if(!$handanliang){
            if(isMobile()){
                return redirect('mlogin');
            }else{
                return redirect('login');
            }
        }else if($handanliang->alltraid >= 30){ 
            return redirect('home?id='.$id);
        }
        
        $ziliaotype = 0;
        $userinfo = DB::table('waihui_member')
                ->select('isvip','photo','introduction','jifen','reg_time','grade','alltraid','id','tel','username','hasapply','applytime','sex','email','birthday','server_name','expire_time')
                ->where('id','=',$id)
                ->first();
        
        if(!$userinfo){
            $ziliaotype = 1;
        }else{
            $moreinfo = DB::table('waihui_member_info')->select('province','city','country')->where('userid','=',$id)->first();
            if(!$moreinfo){
                $ziliaotype = 1;  //资料未全部完善
            }else if($userinfo->username == '' || $userinfo->sex == '' || $userinfo->email == ''|| $userinfo->birthday == '' || $moreinfo->province == '' || $moreinfo->city == '' || $moreinfo->country == '' || $userinfo->server_name == ''){
                $ziliaotype = 1;  //资料未全部完善
            }else{
                $ziliaotype = 0;
            }
        }
        if($ziliaotype == 1){
        
            if(isMobile()){
                return redirect('/baseinfo?id='.$id);
            }else{
                return redirect('/authenticate?id=no');
            }
           
        }else{  //如果用户的资料已完善，那么展示客户的用户中心
            $userinfo->reg_time = date('Y-m-d H:i:s',$userinfo->reg_time);
            //总收益
            $allprofit = allProfitData($userinfo->tel);


            //跟单总收益
            $gendanProfit = gendanAllProfit($userinfo->tel);
           
            //正在订阅
            $mefollowdata = UCenterController::GenSui($id);
           
           
            //日报表
            $daysstr    = $this->dailySheet($userinfo->tel)[0];
            $buynumstr  = $this->dailySheet($userinfo->tel)[1];
            $sellnumstr = $this->dailySheet($userinfo->tel)[2];

            //$monthfirst = strtotime(date('Y-m-01 00:00:00'));
            
            //交易品种
            $typenames   = $this->allTradeTypename($userinfo->tel)[0];
            $typenamestr = $this->allTradeTypename($userinfo->tel)[1];
            
            //总盈利交易
            $data['allProfitTrade'] = $allProfitTrade =$this->allMyProfitTrade($userinfo->tel);
            
            //总交易，总盈利交易，总亏损交易
            $allTrade = $this->allTrade($userinfo->tel);
            
            //总交易
            $all = DB::table('waihui_order')
                        ->select(DB::raw("count(CASE WHEN buy_status='0' THEN 1 END) AS buynum"),DB::raw("count(CASE WHEN buy_status='1' THEN 1 END) AS sellnum"))
                        ->where([['tel','=',"$userinfo->tel"],['isstop','=',0],['ispersonal','=',0]])
                        ->first();
            
            if($all){
                $data['buy_num'] = $all->buynum; //买多数量
                $data['sell_num'] = $all->sellnum; //买空数量
                $allnum = $all->buynum + $all->sellnum ? $all->buynum + $all->sellnum : 0;
            }else{
                $data['buy_num'] = 0; //买多数量
                $data['sell_num'] = 0; //买空数量
                $allnum = 0;
            }
            $data['allnum'] = $allnum;
            
           
            if($allnum != 0){
                $data['left1_red'] = round(($allnum / 30)*100,0);
                $data['left1_gray'] = round((100 - $data['left1_red']),0);
                $data['dingjiLeft'] = round(($allnum / 30)*100,0);
                //$data['dingjiRight'] = round((100 - $data['dingjiLeft']),0);
            }else{
                $data['left1_red'] = 0;
                $data['dingjiLeft'] = 0;
                $data['left1_gray'] = 100;
            }
            
            //订阅者总数
            $follownum    = DB::table('waihui_follow')->where([['analyst_id','=',$userinfo->id],['status','=',1]])->count();
            $follownum = $follownum ? $follownum : 0;
            if($sessionData['id'] == $id){
                $isself = 1;
            }else{
                $isself = 0;
            }
            $tiyan = $userinfo->expire_time; //会员到期时间
            if(isMobile()){
                //获取总收益、总单量、正在订阅分析师数量、本周总收益
                $mobgendaninfo   = MobileCustomerInfo($userinfo->id,$userinfo->tel);
//                return view('mobile.customer',  compact('id','typenames','follownum','data','typenamestr','mefollowdata','daysstr','buynumstr','sellnumstr','tiyan','userinfo','moreinfo','allprofit','gendanProfit','isself'));
                return view('newmobile.customer',  compact('id','typenames','follownum','data','typenamestr','mefollowdata','daysstr','buynumstr','sellnumstr','tiyan','userinfo','moreinfo','allprofit','gendanProfit','isself','mobgendaninfo'));
            }else{
                return view('user.myhome',  compact('id','typenames','follownum','data','typenamestr','mefollowdata','daysstr','buynumstr','sellnumstr','tiyan','userinfo','moreinfo','allprofit','gendanProfit','isself'));
            }
        }
    }

    //客户个人中心 历史跟随
    public function historyFollow(Request $request){
        /*历史订阅 start*/
        $pagesize = 10;
        $page     = intval(trim($request->page)) ? intval(trim($request->page)) :1;
        $offset   = ($page-1)*$pagesize;
        $id = intval(trim($request->id)) ? intval(trim($request->id)) : $request->session()->get('eai')['id'];
        $type = intval($request->type)?intval($request->type):0;
        if($type == 1){ //正向
            $where['f.direction'] = 0;
        }else if($type == 2){ //反向
            $where['f.direction'] = 1;
        }
        $where['f.follower_id'] = $id;
        $where['f.status'] = 0;
        $totalnum  = DB::table('waihui_follow as f')->join('waihui_member as m','f.analyst_id','m.id')->where($where)->count();
        $totalpage = ceil($totalnum/$pagesize);
        $historyfollowdata =  DB::table('waihui_follow as f')
                                ->join('waihui_member as m','f.analyst_id','m.id')
                                ->select('f.analyst_id','f.direction','m.tel','m.photo','m.username')
                                ->where($where)->orderBy('f.analyst_id','desc')->offset($offset)->limit($pagesize)->get();
        if($totalnum && $historyfollowdata) {
            foreach ($historyfollowdata as $hkey => $hval) {
                $latelyorder = DB::table('waihui_order')->where(array('tel' => $hval->tel))->select('begin_time')->orderBy('id', 'desc')->first();
                $historyfollowdata[$hkey]->latelyordertime = $latelyorder?$latelyorder->begin_time:0; //最近交易时间
                $orderinfo   = DB::table('waihui_order')->select(DB::raw('count("o.tel") as dealcounts'),DB::raw('max(final_point) as max_final_point'),DB::raw('min(final_point) as min_final_point'))->where(array('tel' => $hval->tel))->get()->toArray();
                $historyfollowdata[$hkey]->dealcounts      = $orderinfo[0]->dealcounts;
                $historyfollowdata[$hkey]->max_final_point = $orderinfo[0]->max_final_point;
                $historyfollowdata[$hkey]->min_final_point = $orderinfo[0]->min_final_point;
                $finalinfo   = DB::table('waihui_gendan')->where(array('analyst_tel' => $hval->tel))->select(DB::raw('SUM(profit) as final_profit'))->get()->toArray();
                if ($finalinfo) {
                    $historyfollowdata[$hkey]->final_profit = $finalinfo[0]->final_profit;
                } else {
                    $historyfollowdata[$hkey]->final_profit = 0;
                }
            }
        }else{
            $historyfollowdata = [];
        }
        return view('user.historyfollow',compact('historyfollowdata','type','page','totalpage'));
        /*历史订阅 end*/
    }

    
    //客户个人中心 历史跟随 ----新版个人中心
    public function newhistoryFollow(Request $request){
        /*历史跟随 start*/
        $pagesize = 10;
        $page     = intval(trim($request->page)) ? intval(trim($request->page)) :1;
        $offset   = ($page-1)*$pagesize;
        $id = intval(trim($request->id)) ? intval(trim($request->id)) : $request->session()->get('eai')['id'];
        $tel = DB::table('waihui_member')->where('id',$id)->value('tel');
        $type = intval($request->type)?intval($request->type):0;
        if($type == 1){ //正向
            $where['f.direction'] = 0;
        }else if($type == 2){ //反向
            $where['f.direction'] = 1;
        }
        $where['f.follower_id'] = $id;
        $where['f.status'] = 0;
        $totalnum  = DB::table('waihui_follow as f')->join('waihui_member as m','f.analyst_id','m.id')->where($where)->count();
        $totalpage = ceil($totalnum/$pagesize);
        $historyfollowdata =  DB::table('waihui_follow as f')
                                ->join('waihui_member as m','f.analyst_id','m.id')
                                ->select('f.direction','m.tel','m.photo','m.username','m.id','m.authstatus')
                                ->where($where)->orderBy('f.analyst_id','desc')->offset($offset)->limit($pagesize)->get();
        if($totalnum && $historyfollowdata) {
            foreach ($historyfollowdata as $hkey => $hval) {
                $latelyorder = DB::table('waihui_order')->where(array('tel' => $hval->tel))->select('begin_time')->orderBy('id', 'desc')->first();
                $historyfollowdata[$hkey]->latelyordertime = $latelyorder?$latelyorder->begin_time:0; //最近交易时间
                 
                $orderinfo   = DB::table('waihui_gendan')
                             ->select(
                                        DB::raw('count(id) as dealcounts'),
                                        DB::raw('max(profit) as max_final_point'),
                                        DB::raw('min(profit) as min_final_point'),
                                        DB::raw("round(SUM(profit)/count(id),2) as avg_final_point"),
                                        DB::raw('SUM(profit) as zong_final_point')
                                     )
                             ->where([['analyst_tel','=',$hval->tel],['follower_tel','=',$tel],['isstop','=',0]])
                             ->get()->toArray();
                $historyfollowdata[$hkey]->dealcounts      = $orderinfo[0]->dealcounts;
                $historyfollowdata[$hkey]->max_final_point = $orderinfo[0]->max_final_point;
                $historyfollowdata[$hkey]->min_final_point = $orderinfo[0]->min_final_point;
                $historyfollowdata[$hkey]->avg_final_point = $orderinfo[0]->avg_final_point;
                $historyfollowdata[$hkey]->zong_final_point = $orderinfo[0]->zong_final_point;
                
                //$finalinfo   = DB::table('waihui_gendan')->where(array('analyst_tel' => $hval->tel))->select(DB::raw('SUM(profit) as final_profit'))->get()->toArray();
//                if ($finalinfo) {
//                    $historyfollowdata[$hkey]->final_profit = $finalinfo[0]->final_profit;
//                } else {
//                    $historyfollowdata[$hkey]->final_profit = 0;
//                }
            }
        }else{
            $historyfollowdata = [];
        }
        
        // dd($historyfollowdata);
        if(isMobile()) {
            if(trim($request->pagetype) == 1){
                return json_encode(array('historyfollowdata'=>$historyfollowdata,'type'=>$type,'totalpage'=>$totalpage,'id'=>$id));
            }else{
               return view('newmobile.newhistoryfollow',compact('historyfollowdata','type','page','totalpage','id')); 
            }
        }else{
            return view('user.newhistoryfollow',compact('historyfollowdata','type','page','totalpage'));
        }
        /*历史跟随 end*/
    }
    
    
    public function UserCenter(Request $request){  //分析师的用户中心
        $type = htmlspecialchars(trim($request->get('type')));
        $uid = intval($request->get('id'));
       
        if(!$uid || $uid == 0){
            	if(isMobile()){
        		return redirect('mobile.analyst');
        	}else{
        		return redirect('bdlists');
        	}
        }
        $sessionData = $request->session()->get('eai');

//        $tiyan = getenv('tiyan');  //申请体验账户天数
        $handanliang = DB::table('waihui_member')->select('alltraid')->where('id','=',$uid)->first(); //查询喊单量,并且判断当前用户是否存在
        if(!$handanliang){
             return redirect('bdlists');
        }
        if($type){    //分析师自己看自己的个人中心
            if($type != 'user' || !$sessionData['id']){  //非法输入
                if(isMobile()){
            		return redirect('mlogin');
            	}else{
            		return redirect('login');
            	}
            }else if($sessionData['id'] != $uid){
                if($handanliang->alltraid < 30){
                    return redirect('kehuhome?id='.$uid);
                }else{
                    return redirect('analysthome?id='.$uid);
                }
            }else if($handanliang->alltraid < 30){
                return redirect('kehuhome?type=user&id='.$uid);
            }
            
//            $gendanProfit = gendanAllProfit($sessionData['tel']);  //跟单盈利点位
//            $gendanData = gendanAllData($sessionData['tel']);      //跟单数据
     
        }else{
            $type = ''; 
            if($sessionData['id'] == $uid){
                if($handanliang->alltraid < 30){
                    return redirect('kehuhome?type=user&id='.$uid);
                }else{
                    return redirect('analysthome?type=user&id='.$uid);
                }
            }else{
                if($handanliang->alltraid < 30){
                    return redirect('kehuhome?id='.$uid);
                }
            }
            
        }  

        //判断有没有该分析师
        $userinfo = DB::table('waihui_member')->select('*')->where('id','=',$uid)->first();
        if(!$userinfo){
            if(isMobile()){
        	return redirect('mobile.analyst');
            }else{
        	return redirect('bdlists');
            }
        }else{

//            $hasAppayDel = DB::table('waihui_deltop20')->where('userid','=',$uid)->first(); //是否申请过删除前20条喊单记录
//            if(!$hasAppayDel){
//                $hasAppayDel = 0;
//            }else{
//               $hasAppayDel = 1; 
//            }

            $moreinfo = DB::table('waihui_member as m')
                    ->join('waihui_member_info as i','m.id','=','i.userid')                   
                    ->select('i.province','i.city','i.country')
                    ->where('m.id','=',$uid)
                    ->first();
            $moreinfo = $moreinfo ? $moreinfo : '';
           
        }
        $userinfo->reg_time = date('Y-m-d',$userinfo->reg_time);
        
        //擅长品种 
        $memadepttype   = memAdeptType($userinfo->tel,5); 

        //查询用户擅长短线，中线还是长线交易
        $LineAndPoint = $this->linePoint($userinfo->tel);
        $lastPoint = json_decode($LineAndPoint);
        $likeLine = ((($lastPoint->shortLine > $lastPoint->centerLine) ? $lastPoint->shortLine : $lastPoint->centerLine) > $lastPoint->longLine) ? (($lastPoint->shortLine > $lastPoint->centerLine) ? '短线' :'中线') : '长线';

        //跟随者总数
        $follownum    = DB::table('waihui_follow')->where([['analyst_id','=',$uid],['status','=',1]])->count();
        $follownum = $follownum ? $follownum : 0;
        
        //跟随者信息
//        $fwhere['f.analyst_id'] = $uid;
//        $fwhere['f.status']     = 1; //已订阅
//        $followdata   = DB::table('waihui_follow as f')
//                        ->join('waihui_member as m','f.follower_id','=','m.id')
//                        ->select('m.photo','m.username')
//                        ->where($fwhere)
//                        ->limit(6)->get()->toArray();
//                        
        //总盈利点位（只算盈利的）和总盈利交易,做多交易总单量，做空交易总单量
        $allData = $this->allTrade($userinfo->tel);
        $maxData = $this->maxDada($userinfo->tel); //最达连胜，最大连亏,最大涨幅，最大回撤
        $wenDing_fengXian = $this->wenDindZhi($userinfo->tel); //稳定值和风险比
        $timeDistribution = $this->timeDistribution($userinfo->tel);//时间分布，亚盘、欧盘、美盘

        
        //交易品种
        $typenames   = $this->allTradeTypename($userinfo->tel)[0];
        $typenamestr = $this->allTradeTypename($userinfo->tel)[1];
        
        //日报表
        $daydeal = $this->dailySheet($userinfo->tel);
        //$daysstr    = $this->dailySheet($userinfo->tel)[0];
//        $buynumstr  = $this->dailySheet($userinfo->tel)[1];
//        $sellnumstr = $this->dailySheet($userinfo->tel)[2];
       // $numstr     = $this->dailySheet($userinfo->tel)[3];


        //周报表
        $weekdeal  = $this->weeklySheet($userinfo->tel);
        
        //点位区间图
        $pointBetweenChat = $this->pointBetweenChat($userinfo->tel);
        
        
        //总交易报表
        $timeDayJiaoyi  = $this->allTotalData($userinfo->tel)[0];
        $pointDayJiaoyi = $this->allTotalData($userinfo->tel)[1];
        
        
        $gotogendan = $request->gotogendan ? $request->gotogendan:0;
        $isdingyue  = DB::table('waihui_follow')->where([['analyst_id','=',$uid],['follower_id','=',$sessionData['id']],['status','=',1]])->first(); //订阅该分析师的状态
        if($isdingyue){
            $followstatus    = $isdingyue->status;
            $followdirection = $isdingyue->direction;
        }else{
            $followstatus    = 3; //未订阅
            $followdirection = 3;
        }
        

        //盈亏图
        $plarr         = $this->profitLoss($userinfo->tel);
        $pltimestr     = $plarr[0];
        $plpointstr    = $plarr[1];
        $profitpointstr= $plarr[2];
        $losspointstr  = $plarr[3];

        //分析师K线图
        $kstr = $this->allPoint($userinfo->tel);

        // 跟随分析师
        $mefollowdata = UCenterController::newGenSui($sessionData['id']);

        //交易时间分布图
        $deltimemap   = $this->delTimeMap($userinfo->tel);
        $delpointstr  = $deltimemap[0];
        $deltimetstr  = $deltimemap[1];
        $delwinratestr= $deltimemap[2];
        
        $dingYueInfo = $this->genSuiInfo($userinfo->tel);
        //总收益
        $allprofit = allProfitData($userinfo->tel);
        //总交易
        $all = DB::table('waihui_order')
                    ->select(DB::raw("count(CASE WHEN buy_status='0' THEN 1 END) AS buynum"),DB::raw("count(CASE WHEN buy_status='1' THEN 1 END) AS sellnum"))
                    ->where([['tel','=',"$userinfo->tel"],['isstop','=','0'],['ispersonal','=',0]])
                    ->first();
        //dd($all);
        if($all){
            $data['buy_num'] = $all->buynum; //买多数量
            $data['sell_num'] = $all->sellnum; //买空数量
            $allnum = $all->buynum + $all->sellnum ? $all->buynum + $all->sellnum : 0;
        }else{
            $data['buy_num'] = 0; //买多数量
            $data['sell_num'] = 0; //买空数量
            $allnum = 0;
        }
      
        $data['allnum'] = $allnum;   
        
        $id = $uid; //此处是为了让客户的用户中心和分析师的个人中心公用订阅大师的页面
	    if(isMobile()){
            $memdelinfo = memDelInfo($userinfo->tel);
            return  view('mobile.analystcenter',  compact('memdelinfo','timeDayJiaoyi','pointDayJiaoyi','mefollowdata','followstatus','followdirection','tiyan','gendanData','gendanProfit','type','allLosspoint','allProfitpoint','total','weekdeal','monthsstr','monthfinalpointstr','typenames','typenamestr','daysstr','buynumstr','sellnumstr','daydeal','data','userinfo','moreinfo','allprofit','followdata','follownum','gotogendan'));
        }else{
            //return view('usercenter.home',  compact('id','hasAppayDel','timeDayJiaoyi','pointDayJiaoyi','mefollowdata','followstatus','followdirection','tiyan','gendanData','gendanProfit','type','allLosspoint','allProfitpoint','total','weekdeal','monthsstr','monthfinalpointstr','typenames','typenamestr','daysstr','buynumstr','sellnumstr','daydeal','data','userinfo','moreinfo','allprofit','followdata','follownum','gotogendan'));
            return view('usercenter.home',  compact('dingYueInfo','id','memadepttype','userinfo','moreinfo','LineAndPoint','likeLine','follownum','allData','maxData','wenDing_fengXian','timeDistribution','timeDayJiaoyi','pointDayJiaoyi','daydeal','pltimestr','plpointstr','profitpointstr','losspointstr','typenames','typenamestr','kstr','weekdeal','delpointstr','deltimetstr','delwinratestr','followstatus','followdirection','pointBetweenChat','mefollowdata'));
        }
    }
    
    
    public function GenSui($id){  //我订阅的分析师
            $mefollowdata = DB::table('waihui_follow as f')
                ->select('f.analyst_id','f.analyst_name','f.status','f.direction','m.photo','m.username','m.tel','f.follow_time','f.update_time')
                ->join('waihui_member as m','f.analyst_id','m.id')
                ->where([['f.follower_id','=',$id],['f.status','=',1]])
                ->get()->toArray(); //我订阅的分析师
            
           
            foreach ($mefollowdata as $key=>$val){
                $followorderdata = DB::table('waihui_order')
                                   ->select(DB::raw("count(id) as ordernum"),DB::raw("(count(case when trade_status='1' then 1 end) / count(tel))*100 AS winrate"),DB::raw("max(final_point) as max_final_point"),DB::raw("min(final_point) min_final_point"),DB::raw("(SUM(final_point)+COUNT(id)*5) AS zong_final_point"))
                                   ->where('tel','=',$val->tel)->get()->toArray();
                $mefollowdata[$key]->ordercount      = $followorderdata[0]->ordernum;
                $mefollowdata[$key]->winrate         = $followorderdata[0]->winrate;
                $mefollowdata[$key]->max_final_point = $followorderdata[0]->max_final_point;
                $mefollowdata[$key]->min_final_point = $followorderdata[0]->min_final_point;
                $mefollowdata[$key]->zong_final_point = $followorderdata[0]->zong_final_point;
                //获取用户跟单收益
                $selftel    = DB::table('waihui_member')->where(array('id'=>$id))->value('tel');
                $gendandata = DB::table('waihui_gendan as g')
                                ->join('waihui_order as o','o.tradeid','g.tradeid')
                                ->select(DB::raw('(sum(o.final_point)+COUNT(o.id)*5) as final_point'))
                                ->where([['g.isstop','=','0'],['g.follower_tel','=',$selftel],['g.analyst_tel','=',$val->tel]])
                                ->pluck('final_point');
                $mefollowdata[$key]->final_point     = $gendandata[0];
            }
            return $mefollowdata;
    }
    
     public function newGenSui($id){  //我跟随的分析师  --新版个人中心
            $tel = DB::table('waihui_member')->where('id',$id)->value('tel');
            
            if(!$tel){
                redirect('bdlist');
            }
            //DB::connection()->enableQueryLog();
        
            $mefollowdata = DB::table('waihui_follow as f')
                         ->select('f.analyst_id','f.status','f.direction','m.photo','m.username','m.tel','f.follow_time','f.update_time')
                         ->join('waihui_member as m','f.analyst_id','m.id')
                         ->where([['f.follower_id','=',$id],['f.status','=',1]])
                         ->get()->toArray(); //我订阅的分析师
           
        //$queries = DB::getQueryLog();
        
            //dd($queries);
           
            foreach ($mefollowdata as $key=>$val){
                $followorderdata = DB::table('waihui_gendan')
                                   ->select(DB::raw("count(id) as ordernum"),
                                           DB::raw("(count(case when profit>0 then 1 end) / count(id))*100 AS winrate"),
                                           DB::raw("round(SUM(profit)/count(id),2) as avg_final_point"),
                                           DB::raw("round(SUM(profit),2) AS zong_final_point")
                                    )
                                   ->where([['analyst_tel','=',$val->tel],['follower_tel','=',$tel],['isstop','=',0]])
                                   ->get()->toArray();
                
                $trendpointobj  = DB::table('waihui_gendan')
                                ->select(DB::raw('SUM(`profit`) as final_point'),DB::raw("FROM_UNIXTIME(end_time, '%Y-%m-%d') AS days"))
                                ->where([['analyst_tel','=',$val->tel],['follower_tel','=',$tel],['isstop','=',0]])
                                ->groupBy('days')
                                ->get()->toArray();
                $timearr  = [];
                $pointarr = [];
                $pointcount = 0;
                foreach ($trendpointobj as $tkey=>$tval){
                    $timearr[]  = $tval->days;
                    $pointcount = $pointcount+$tval->final_point;
                    $pointarr[] = round($pointcount,2);
                }
                $mefollowdata[$key]->timesstr     = implode(',',$timearr);
                $mefollowdata[$key]->pointstr     = implode(',',$pointarr);
            
                
                $mefollowdata[$key]->ordercount      = $followorderdata[0]->ordernum;
                $mefollowdata[$key]->winrate         = $followorderdata[0]->winrate;
                $mefollowdata[$key]->avg_final_point = $followorderdata[0]->avg_final_point;
                $mefollowdata[$key]->zong_final_point = $followorderdata[0]->zong_final_point;
                
            }
            //dd($mefollowdata);
            return $mefollowdata;
    }
    
            


    //策略记录
    public function handanHistory(Request $request){
	if(isMobile()){
	     $pagesize  = 10;
	}else{
	     $pagesize  = 8;
	}
//        $tel       = trim($request->analyst_tel);
        $id        = intval(trim($request->analyst_id));
        $id        = $id ? $id:$request->session()->get('eai')['id'];
        $tel       = DB::table('waihui_member')->where(array('id'=>$id))->value('tel');
        $type      = trim($request->type);
        $dealtype  = trim($request->dealtype);
        $typename  = trim($request->typename) ? trim($request->typename) : null;
        $page      = intval(trim($request->page)) ? intval(trim($request->page)) :1;
        $offset    = ($page-1)*$pagesize;
        $data['page'] = $page;
        
        $arr = [];
        $where['o.tel'] = $tel;
        if($type == 1){
            $where['o.buy_status'] = '0';
        }else if($type == 2){
            $where['o.buy_status'] = '1';
        }
        if($dealtype == 1){
            $where['o.trade_status'] = '1';
        }else if($dealtype == 2){
            $where['o.trade_status'] = '0';
        }
        if($typename){
            $where['o.typename'] = $typename;
        }
        $where['o.isstop']=0;
        $where['o.ispersonal']=0;
        $data['allnum'] =  DB::table('waihui_order as o')
                    ->where($where)
                    ->count('id');
        $data['allpage'] = ceil($data['allnum']/$pagesize);
        
        
        if($tel){
            DB::connection()->enableQueryLog(); // 开启查询日志  
            $data['arr'] =  DB::table('waihui_order as o')
                    ->join('waihui_type as t','t.name','o.typename')
                    ->select('t.chinaname','o.id','o.tradeid','o.tel','o.begin_time','o.begin_point','o.end_point','o.end_time','o.buy_status','o.typename','o.target_profit_point','o.target_loss_point','o.final_point')
                    ->where($where)
                    ->orderBy('o.end_time','desc')
                    ->orderBy('o.id','desc')
                    ->offset($offset)
                    ->limit($pagesize)
                    ->get();
            //dd($data['arr']);        
            //DB::table('waihui_order'); // 要查看的sql 
            //$queries = DB::getQueryLog(); 
            //dd($data['arr']);
        }
       
        return json_encode($data);
    }
    //订阅者
    public function followerList(Request $request){
        $pagesize = 12;
        $type   = trim($request->type);
        $uid   = trim($request->analyst_id);
        $page   = trim($request->page);
        if(intval($page) == 0){
            $page = 1;
        }
        
        if($type != 0 && $type != 1){
            $offset = 0;
        }else{
            $offset = ($page-1)*$pagesize;
        }
        //dd($offset);
        $allnum = DB::table('waihui_follow')  //总数量
                ->select(DB::raw('count(id) as num'))
                ->where([['analyst_id','=',$uid],['status','=','1']])
                ->pluck('num');
        if($allnum && $allnum[0]){
            $allnum = $allnum[0];
            $totalpage = ceil($allnum /$pagesize);
        }else{
            $allnum = 0;
            $totalpage = 0;
        }
                
        $fwhere['f.analyst_id'] = $uid;
        $fwhere['f.status']     = 1; //已订阅
        $analystTel  =  DB::table('waihui_member')
                        ->select('tel')
                        ->where('id','=',$uid)
                        ->pluck('tel');
        if(!$analystTel){
            return false;
        }
        $followdata   = DB::table('waihui_member as m')
                        ->join('waihui_follow as f','f.follower_id','=','m.id')
                        ->select('m.photo','m.username','f.follower_id','m.tel','f.direction','f.follow_time')
                        ->where($fwhere)
                        ->orderBy('f.follow_time')
                        ->groupBy('f.follower_id')
                        ->offset($offset)
                        ->limit(12)
                        ->get();
        
        foreach ($followdata as $key=>$val){
            //DB::connection()->enableQueryLog();
            $data = DB::table('waihui_gendan as g')
                        ->join('waihui_order as o','o.tradeid','g.tradeid')
                        ->select(DB::raw('(sum(o.final_point)+COUNT(o.id)*5) as allnum'))
                        ->where([['g.isstop','=','0'],['g.follower_tel','=',$val->tel],['g.analyst_tel','=',$analystTel[0]]])
                        ->pluck('allnum');

             
            //DB::table('waihui_gendan'); // 要查看的sql 
           // $queries = DB::getQueryLog(); // 获取查询日志
//            dd($queries);
            
            if($data && $data[0]!=''){
                 $followdata[$key]->allnum =round($data[0],2);
            }else{
                $followdata[$key]->allnum = 0;
            }
             
        }
        if(isMobile()){
        	
        	return view('mobile.merchandiser',compact('page','totalpage','allnum','followdata','uid'));
        }else{
        	return view('usercenter.follow',compact('page','totalpage','allnum','followdata','uid'));
        }   
    }
    //我的订阅
    public function gendanList(Request $request){
        $pagesize  = 10;
//        $tel       = $request->session()->get('eai')['tel'];
//        if(!$tel){
//            if(isMobile()){
//                return redirect('mlogin');
//            }else{
//                return redirect('login');
//            }
//        }
        $id        = intval(trim($request->analyst_id));
        $id        = $id?$id:$request->session()->get('eai')['id'];
        $tel       = DB::table('waihui_member')->where(array('id'=>$id))->value('tel');
        $type      = intval(trim($request->type)) ? intval(trim($request->type)) : '';
        $dealtype  = trim($request->dealtype);
        $typename  = trim($request->typename);
        $page      = intval(trim($request->page)) ? intval(trim($request->page)) :1;
        $pagetype  = intval(trim($request->pagetype));
        if($pagetype == 0 && $page == 1){
            $offset = 0;
        }else if($pagetype == 1){
            $offset = ($page-1)*$pagesize;
        }else{
            $page   = $page-2;
            $offset = ($page-2)*$pagesize;
        }

        $where['g.follower_tel'] = $tel;
        if($type == 1){
            $where['o.buy_status'] = '0';
        }else if($type == 2){
            $where['o.buy_status'] = '1';
        }
        
        if($dealtype == 1){
            $whereprofit ='>';
        }else if($dealtype == 2){
            $whereprofit = '<';
        }else{
            $whereprofit = "!=";
        }
        if($typename){
            $where['g.typename'] = $typename;
        }
        $where['g.isstop'] = 0;

        $allnum    =  DB::table('waihui_gendan as g')   //订阅记录
                        ->join('waihui_order as o','o.tradeid','=','g.tradeid')
                        ->where($where)
                        ->where('g.profit',$whereprofit,'')
                        ->count('g.id');
        $totalpage = ceil($allnum/$pagesize);

        $gendandata  =  DB::table('waihui_gendan as g')
                        ->join('waihui_order as o','o.tradeid','=','g.tradeid')->join('waihui_type as t','t.name','o.typename')
                    	->join('waihui_member as m','m.tel','=','g.analyst_tel')
                        ->select('m.username','t.chinaname','g.tradeid','g.begin_time','g.begin_point','g.end_point','g.end_time','o.buy_status','g.typename','g.target_profit_point','g.target_loss_point','g.profit')
                        ->where($where)
                        ->where('g.profit',$whereprofit,'')
                        ->orderBy('g.end_time','desc')
                        ->offset($offset)
                        ->limit($pagesize)
                        ->get();

        //交易品种
        $typenames  = DB::table('waihui_gendan as g')
                        ->join('waihui_type as t','g.typename','t.name')
                        ->select('t.chinaname','g.typename')
                        ->where(array('g.follower_tel'=>$tel,'g.isstop'=>0))
                        ->groupBy('g.typename')
                        ->get()->toArray();
            

        
        if(isMobile()){
        	return json_encode(array('arr'=>$gendandata,'allpage' => $totalpage));
        }else{
        	return view('usercenter.gendan',compact('page','totalpage','allnum','gendandata','typenames','type','dealtype','typename'));
   		}
    }

    // 新个人中心跟单记录
    public function newgendanList(Request $request){
    $pagesize  = 10;
//        $tel       = $request->session()->get('eai')['tel'];
//        if(!$tel){
//            if(isMobile()){
//                return redirect('mlogin');
//            }else{
//                return redirect('login');
//            }
//        }
    $id        = intval(trim($request->analyst_id));
    $id        = $id?$id:$request->session()->get('eai')['id'];
    $tel       = DB::table('waihui_member')->where(array('id'=>$id))->value('tel');
    $type      = intval(trim($request->type)) ? intval(trim($request->type)) : '';
    $dealtype  = trim($request->dealtype);
    $typename  = trim($request->typename);
    $page      = intval(trim($request->page)) ? intval(trim($request->page)) :1;
    $pagetype  = intval(trim($request->pagetype));
    if($pagetype == 0 && $page == 1){
        $offset = 0;
    }else if($pagetype == 1){
        $offset = ($page-1)*$pagesize;
    }else{
        $page   = $page-2;
        $offset = ($page-2)*$pagesize;
    }

    $where['g.follower_tel'] = $tel;
    if($type == 1){
        $where['o.buy_status'] = '0';
    }else if($type == 2){
        $where['o.buy_status'] = '1';
    }

    if($dealtype == 1){
        $whereprofit ='>';
    }else if($dealtype == 2){
        $whereprofit = '<';
    }else{
        $whereprofit = "!=";
    }
    if($typename){
        $where['g.typename'] = $typename;
    }
    $where['g.isstop'] = 0;

    $allnum    =  DB::table('waihui_gendan as g')   //跟单记录
    ->join('waihui_order as o','o.tradeid','=','g.tradeid')
        ->where($where)
        ->where('g.profit',$whereprofit,'')
        ->count('g.id');
    $totalpage = ceil($allnum/$pagesize);

    $gendandata  =  DB::table('waihui_gendan as g')
        ->join('waihui_order as o','o.tradeid','=','g.tradeid')->join('waihui_type as t','t.name','o.typename')
        ->join('waihui_member as m','m.tel','=','g.analyst_tel')
        ->select('m.username','t.chinaname','g.tradeid','g.begin_time','g.begin_point','g.end_point','g.end_time','o.buy_status','g.typename','g.target_profit_point','g.target_loss_point','g.profit')
        ->where($where)
        ->where('g.profit',$whereprofit,'')
        ->orderBy('g.end_time','desc')
        ->offset($offset)
        ->limit($pagesize)
        ->get();

    //交易品种
    $typenames  = DB::table('waihui_gendan as g')
        ->join('waihui_type as t','g.typename','t.name')
        ->select('t.chinaname','g.typename')
        ->where(array('g.follower_tel'=>$tel,'g.isstop'=>0))
        ->groupBy('g.typename')
        ->get()->toArray();



    if(isMobile()){
        return json_encode(array('arr'=>$gendandata,'allpage' => $totalpage));
    }else{
        return view('usercenter.newfollow',compact('page','totalpage','allnum','gendandata','typenames','type','dealtype','typename'));
    }
}

    // 新版个人中心订阅者
    public function newDingYue(Request $request){
        $id  = intval(trim($request->analyst_id));
//        $id  = $id ? $id : $request->session()->get('eai')['id'];
        $tel = DB::table('waihui_member')->where('id',$id)->value('tel');
        if(!$id || !$tel){
            return redirect('bdlists');
        }
        
        $now =time();
        $dingYueZhong = DB::table('waihui_follow as f') //正在订阅的会员
                        ->join('waihui_member as m','f.follower_id','=','m.id')
                        ->select('follow_name','direction','follow_time','follower_id','m.photo','m.tel')
                        ->where([['analyst_id','=',$id],['status','=',1],['m.isvip','!=','0'],['m.expire_time','<',$now]])
                        ->groupBy('follower_id')
                        ->get();
        $guoQi = DB::table('waihui_follow as f') //已经过期的会员
                ->join('waihui_member as m','f.follower_id','=','m.id')
                ->select('follow_name','direction','follow_time','follower_id','m.photo','m.tel')
                ->where([['analyst_id','=',$id],['m.isvip','!=','0'],['status','=',0],['m.expire_time','<',$now]])
                ->groupBy('follower_id')
                ->get();
        
        $shiYong =  DB::table('waihui_follow as f') //试用会员
                    ->join('waihui_member as m','f.follower_id','=','m.id')
                    ->select('follow_name','direction','follow_time','follower_id','m.photo','m.tel')
                    ->where([['analyst_id','=',$id],['m.isvip','=','0'],['status','=',1]])
                    ->groupBy('follower_id')
                    ->get();
        
        if($dingYueZhong){
            foreach($dingYueZhong as $k=>$v){
                $shouyi = DB::table('waihui_gendan')
                        ->select(DB::raw('sum(profit) as num'))
                        ->where([['follower_tel','=',$v->tel],['isstop','=',0],['analyst_tel','=',$tel]])
                        ->value('allnum');
                $dingYueZhong[$k]->allnum = $shouyi;
            }
            
        }
        
        if($guoQi){
            foreach($guoQi as $k=>$v){
                $shouyi = DB::table('waihui_gendan')
                        ->select(DB::raw('sum(profit) as num'))
                        ->where([['follower_tel','=',$v->tel],['isstop','=',0],['analyst_tel','=',$tel]])
                        ->value('allnum');
                $guoQi[$k]->allnum = $shouyi;
            }
            
        }
        
        
        if($shiYong){
            foreach($shiYong as $k=>$v){
                $shouyi = DB::table('waihui_gendan')
                        ->select(DB::raw('sum(profit) as num'))
                        ->where([['follower_tel','=',$v->tel],['isstop','=',0],['analyst_tel','=',$tel]])
                        ->value('allnum');
                
                $shiYong[$k]->allnum = $shouyi;
            }
            
        }
        $totalpage = '';
        //dd($dingYueZhong,$guoQi,$shiYong);
        return view('usercenter.newdingyue',compact('dingYueZhong','guoQi','shiYong','totalpage'));
        
    }
    public  function allGendanList(Request $request){   //我的跟单+自主下单

        $pagesize  = 10;
        $id = intval(trim($request->id)) ? intval(trim($request->id)) : 0;
        if($id !=0){
            $tel = DB::table('waihui_member')->where(array('id'=>$id))->value('tel');
        }else{
            $tel = $request->session()->get('eai')['tel'];
        }
        
        if(!$tel){
            if(isMobile()){
                return redirect('mlogin');
            }else{
                return redirect('login');
            }
        }
//        $type      = trim($request->type);  //自主下单1 还是订阅0，默认是订阅
//        if($type == ''){
//            $type = 0;
//        }
        $type = intval(trim($request->type)) ? intval(trim($request->type)) : 0; //自主下单1 ，订阅0，默认是订阅
        $dealtype  = trim($request->dealtype); //盈利，亏损
        
        $typename  = trim($request->typename);
        $page      = intval(trim($request->page)) ? intval(trim($request->page)) :1;
        $pagetype  = intval(trim($request->pagetype));
        
        if($pagetype == 0 && $page == 1){
            $offset = 0;
        }else if($pagetype == 1){
            $offset = ($page-1)*$pagesize;
        }else{
            $page   = $page-2;
            $offset = ($page-2)*$pagesize;
        }
        //dd($type);
        if($type == 0){  //订阅
            $where['g.follower_tel'] = $tel;
            
            if($dealtype == 1){
                $whereprofit =[['g.profit','>',0]];
            }else if($dealtype == 2){
                $whereprofit = [['g.profit','<',0]];
            }else{
                $whereprofit = [];
            }

            if($typename){
                $where['g.typename'] = $typename;
            }
            $where['g.isstop'] = 0;
            
            $allnum = DB::table('waihui_gendan as g')   //订阅记录
                    ->join('waihui_order as o','o.tradeid','=','g.tradeid')
                    ->where($where)
                    ->where($whereprofit)
                    ->count('g.id');

            $gendandata  =  DB::table('waihui_gendan as g')
                        ->join('waihui_order as o','o.tradeid','=','g.tradeid')
                        ->join('waihui_member as m','m.tel','=','g.analyst_tel')
                        ->select('m.username','g.tradeid','g.begin_time','g.begin_point','g.end_point','g.end_time','o.buy_status','g.typename','g.target_profit_point','g.target_loss_point','g.profit')
                        ->where($where)
                        ->where($whereprofit)
                        ->orderBy('g.end_time','desc')
                        ->offset($offset)
                        ->limit($pagesize)
                        ->get();

             //交易品种
            $typenames  = DB::table('waihui_gendan as g')
                        ->join('waihui_type as t','g.typename','t.name')
                        ->select('t.chinaname','g.typename')
                        ->where(array('g.follower_tel'=>$tel,'g.isstop'=>0))
                        ->groupBy('g.typename')
                        ->get()->toArray();
            
        }else{
            $where['tel']      = $tel;
            $where['isstop'] = 0;
            $where['ispersonal'] = 1;
            if($dealtype == 1){
                $whereprofit =[['money','>',0]];
            }else if($dealtype == 2){
                $whereprofit = [['money','<',0]];
            }else{
                $whereprofit = [];
            }
            if($typename){
                $where['typename'] = $typename;
            }
            
            
            $allnum =  DB::table('waihui_order')   //自主下单记录
                        ->where($where)
                        ->where($whereprofit)
                        ->count('id');
            
            $gendandata = DB::table('waihui_order')
                        ->select('tradeid','begin_time','begin_point','end_point','end_time','buy_status','typename','target_profit_point','target_loss_point','money')
                        ->where($where)
                        ->where($whereprofit)
                        ->orderBy('end_time','desc')
                        ->offset($offset)
                        ->limit($pagesize)
                        ->get();
            
             //交易品种
            $typenames  = DB::table('waihui_order as o')
                        ->join('waihui_type as t','o.typename','t.name')
                        ->select('t.chinaname','o.typename')
                        ->where(array('o.tel'=>$tel,'o.isstop'=>0))
                        ->groupBy('o.typename')
                        ->get()->toArray();
        }
        
        $totalpage = ceil($allnum/$pagesize);
       

            
            
           // dd($gendandata);
            
        return view('usercenter.alltraid',compact('id','type','page','totalpage','allnum','gendandata','typenames','type','dealtype','typename'));
    
    }
    
    //申请体验账户
    public function applyAccount(Request $request){
        $data['status'] = 2;
        $uid = intval(trim($request->uid));
        
        $userinfo = DB::table('waihui_member')
                    ->select('username','hasapply','applytime','sex','email','birthday','server_name')
                    ->where('id','=',$uid)
                    ->first();
        if(!$userinfo){
            $data['status'] = 0;
        }else{
            $moreinfo = DB::table('waihui_member_info')->select('province','city','country')->where('userid','=',$uid)->first();
            if(!$moreinfo){
                $data['status'] = 1;  //资料未全部完善
            }else if($userinfo->username == '' || $userinfo->sex == '' || $userinfo->email == ''|| $userinfo->birthday == '' || $moreinfo->province == '' || $moreinfo->city == '' || $moreinfo->country == '' || $userinfo->server_name == ''){
                $data['status'] = 1;  //资料未全部完善
            }else{
                $tiyan = getenv('tiyan')*24*60*60;
                $applytime = $userinfo->applytime + $tiyan;
                $currtime =time();
                if($userinfo->hasapply == 1 && $applytime >$currtime ){   //已申请体验账户,并且没有过期
                     $data['endtime'] = $applytime;  //到期时间
                     $data['status'] = 3;
                }else if($userinfo->hasapply == 1 && $applytime <$currtime){  //已申请体验账户,并且 已经过期
                     $data['status'] = 4;
                }else if($userinfo->hasapply != 1 && !$userinfo->applytime){
                    $data = array('hasapply'=>1,'applytime'=>$currtime,'expire_time'=>$currtime+$applytime,'isvip'=>'3');
                    $res = DB::table('waihui_member')->where('id','=',$uid)->update($data);
                    if($res){
                        $data['status'] = 2;
                        $data['expire_time'] = $currtime+$applytime;
                    }else{
                        $data['status'] = 0;
                    }
                }
            }
        }
        echo json_encode($data);
        return;
    }

    
    //日报表
    function dailySheet($tel){  //日报表
        $daydeal    = DB::table('waihui_order')
                        ->select(DB::raw("count(id) AS num"),DB::raw("ROUND((SUM(final_point)+COUNT(id)*5),2) AS final_point"),DB::raw("count(CASE WHEN buy_status='0' THEN 1 END) AS buynum"),DB::raw("ROUND(SUM(CASE WHEN buy_status='0' THEN (final_point+5) END),2) AS buy_final_point"),DB::raw("count(CASE WHEN buy_status='1' THEN 1 END) AS sellnum"),DB::raw("ROUND(SUM(CASE WHEN buy_status='1' THEN (final_point+5) END),2) AS sell_final_point"),DB::raw("FROM_UNIXTIME(end_time, '%Y-%m-%d') AS days"))
                        ->where([['tel','=',$tel],['isstop','=',0]])
                        ->whereBetween('end_time', [0, strtotime('now')])
                        ->orderBy('days','desc')
                        ->groupBy('days')
                        ->limit(15)
                        ->get()->toArray();//日报表
        if($daydeal){
            $days    = [];
            $buynum  = [];
            $sellnum = [];
            $num     = [];
            foreach ($daydeal as $dayk=>$dayv){
                array_unshift($days,$dayv->days);
//                $days[]    = $dayv->days;
                $dayv->buy_final_point  = $dayv->buy_final_point?$dayv->buy_final_point:0;
//                $buynum[]  = '{"k":'.$dayv->buy_final_point.',"y":'.$dayv->buynum.'}';
                array_unshift($buynum,'{"k":'.$dayv->buy_final_point.',"y":'.$dayv->buynum.'}');
                $dayv->sell_final_point = $dayv->sell_final_point?$dayv->sell_final_point:0;
//                $sellnum[] = '{"k":'.$dayv->sell_final_point.',"y":'.$dayv->sellnum.'}';
                array_unshift($sellnum,'{"k":'.$dayv->sell_final_point.',"y":'.$dayv->sellnum.'}');
//                $num[] = '{"k":'.$dayv->final_point.',"y":'.$dayv->num.'}';
                array_unshift($num,($dayv->final_point?$dayv->final_point:0).','.$dayv->num);
                $allDayPoint[] = $dayv->final_point ? $dayv->final_point : 0; //15天的总盈亏点位数组
                $yingLiDay[]   = $dayv->final_point > 0 ? 1 : 0;
            }
            
            $yingLiRiBi  = round((array_sum($yingLiDay)/14*100),2); //盈利日(盈利日占比)
            $avgDayPoint = round((array_sum($allDayPoint)/15),2);   //平均每日收益
            $daysstr    = implode(',',$days);
            $buynumstr  = implode(',',$buynum);
            $sellnumstr = implode(',',$sellnum);
            $numstr     = implode(';',$num);
        }else{
            $daysstr    = '';
            $buynumstr  = '';
            $sellnumstr = '';
            $numstr     = '';
            $avgDayPoint = 0;
            $yingLiRiBi  = 0;
        }
        //dd($yingLiRiBi);
        $arr = array($daysstr,$buynumstr,$sellnumstr,$numstr,$avgDayPoint,$yingLiRiBi);
       
        return $arr;
    }
    
    //月报表
    function monthSheet($tel){
        $monthdeal  = DB::table('waihui_order')
                        ->select(DB::raw("count(tel) AS nums"),DB::raw("(SUM(final_point)+COUNT(id)*5) AS final_point"),DB::raw("FROM_UNIXTIME(end_time, '%m') AS months"))
                        ->where([['tel','=',$tel],['isstop','=',0]])
                        ->groupBy('months')
                        ->get()->toArray();
        
        
        if($monthdeal){
            $defaultmonths = array('01'=>'0','02'=>'0','03'=>'0','04'=>'0','05'=>'0','06'=>'0','07'=>'0','08'=>'0','09'=>'0','10'=>'0','11'=>'0','12'=>'0');
            foreach ($defaultmonths as $key=>$val){
                foreach ($monthdeal as $monthv){
                    if($monthv->months == $key){
                        $defaultmonths[$key] = $monthv->final_point?$monthv->final_point:0;
                    }
                }
                $monthfinalpoint[date('Y').'-'.$key]=$defaultmonths[$key];
            }

            $months = array_keys($monthfinalpoint);
            $monthfinalpoint = array_values($monthfinalpoint);
            $monthsstr           = implode(',',$months);
            $monthfinalpointstr  = implode(',',$monthfinalpoint); 
        }else{
            $monthsstr = '';
            $monthfinalpointstr = '';
        }
        
        $arr =array($monthsstr,$monthfinalpointstr);
        return $arr;
    }
    
    //周报表
    function weeklySheet($tel){
        $weekfirst  = strtotime(date("Y-m-d H:i:s",mktime(0,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y"))));
        $cha = 15*7*24*60*60;  //查询近15周，每周的最终盈亏
        $week_begin_time = ($weekfirst - $cha);
        $weekdeal   = DB::table('waihui_order')
                        ->select(DB::raw("(sum(final_point)+COUNT(id)*5) as lastpoint"),DB::raw("week(FROM_UNIXTIME(end_time, '%Y-%m-%d')) as weeks"),DB::raw("count(id) as num"))
                        ->where(array('tel'=>$tel,'isstop'=>0,'ispersonal'=>0))
                        ->whereBetween('end_time', [$week_begin_time, $weekfirst])
                        ->groupBy('weeks')
                        ->get()->toArray();        
        if($weekdeal){
            foreach($weekdeal as $key=>$val){

//                if($val->lastpoint >= 500){
//                    $weekdeal[$key]->percent = '100%';
//                    $weekdeal[$key]->status = 1;
//                }else if($val->lastpoint >=0 && $val->lastpoint < 500){
//                    $weekdeal[$key]->percent = ($val->lastpoint / 500)*100;
//                    $weekdeal[$key]->status = 1;
//                }else if($val->lastpoint <= -500){
//                    $weekdeal[$key]->percent = '100%';
//                    $weekdeal[$key]->status = 0;
//                }else if($val->lastpoint <0 && $val->lastpoint > -500){
//                    $weekdeal[$key]->percent = ($val->lastpoint / -500)*100;
//                    $weekdeal[$key]->status = 0;
//                }
                
                
                $year = date("Y");
                $weekdeal[$key]->start = strtotime($year . 'W' . $val->weeks);
//                $weekdeal[$key]->end = strtotime('+1 week -1 day', $weekdeal[$key]->start);
                $weekdeal[$key]->start = date('m-d',$weekdeal[$key]->start);
//                if($weekdeal[$key]->end > strtotime('now')){
//                    $weekdeal[$key]->end = date('Y-m-d',time());
//                }else{
//                    $weekdeal[$key]->end = date('Y-m-d',$weekdeal[$key]->end);
//                }
                  $danLiang[] = $val->num;
                  $time[]     = $weekdeal[$key]->start;
                  $lastPoint[] =round($val->lastpoint,2); 
                
            }
            if(count($time) != 0){
                $avgPoint = round((array_sum($lastPoint)/count($time)),2); //平均每周收益
            }else{
                $avgPoint = 0;
            }
            $danStr = implode(',',$danLiang);
            $timeStr =implode(',',$time);
            $pointStr = implode(',',$lastPoint);
            
        }else{
            $danStr = '';
            $timeStr = '';
            $pointStr = '';
            $avgPoint = 0;
        }
        $arr = array($danStr,$timeStr,$pointStr,$avgPoint);
        //dd($arr);
        return $arr;
    }
    
    //总交易报表
    function allTotalData($tel){
        $totaldeal  = DB::table('waihui_order')
                        ->select(DB::raw("FROM_UNIXTIME(end_time, '%Y-%m-%d') AS day"),DB::raw("(SUM(final_point)+COUNT(id)*5) AS final_point"))
                        ->where([['tel','=',$tel],['isstop','=',0],['ispersonal','=',0]])
                        ->groupBy('day')
                        ->get()
                        ->toArray();   
//        DB::table('waihui_order'); 
//        $queries = DB::getQueryLog();
//        dd($queries);
        //此处加28800，是为了适应交易报表，加了8个小时
        
//        if($totaldeal){
//            foreach($totaldeal as $k=>$v){
//                
//                $total = $total +$totaldeal[$k]->final_point;
//                $totalJiaoyi[] = ((strtotime($totaldeal[$k]->day)+28800)*1000).'|'.$total;
//            }
//            $totalJiaoyi = implode(',',$totalJiaoyi);
//        }else{
//            $totalJiaoyi = '';
//        }
        $total = 0;
        $timeDay = [];
        $pointarr = [];
        if($totaldeal){
            foreach($totaldeal as $k=>$v){
                $timeDay[] = $totaldeal[$k]->day;
                $total = $total +$totaldeal[$k]->final_point;
                $pointarr[] = round($total,2);
            }
            $timeDayJiaoyi = implode(',',$timeDay);
            $pointDayJiaoyi = implode(',',$pointarr);
        }else{
            $timeDayJiaoyi = '';
            $pointDayJiaoyi = '';
        }
        
        $arr = array($timeDayJiaoyi,$pointDayJiaoyi);
        //dd($arr);
        return $arr;
    }
    
    //交易品种
    function allTradeTypename($tel){
        $typenames  = DB::table('waihui_order as o')
                        ->join('waihui_type as t','o.typename','t.name')
                        ->select('t.chinaname','o.typename',DB::raw("count(o.tel) AS num"),DB::raw("ROUND((SUM(final_point)+COUNT(o.id)*5),2) AS point"))
                        ->where(array('o.tel'=>$tel,'o.isstop'=>0))
                        ->orderBy('point','desc')
                        ->groupBy('o.typename')
                        ->get()->toArray(); 
        if($typenames){
            foreach ($typenames as $typenamek=>$typenamev){
                $typename[] = '{"value":"'.$typenamev->num.'","name":"'.$typenamev->chinaname.'"}';
            }
            $typenamestr = implode(',',$typename);
        }else{
            $typenamestr = '';
        }
        $arr = array($typenames,$typenamestr);
        return $arr;
    }
    
    
    //擅长交易，短线、中线、长线，及各自的盈亏点位
    function linePoint($tel){
        $LineAndPoint = DB::table('waihui_order')
                      ->select(DB::raw("count(CASE WHEN ((end_time-begin_time)/3600)<=48 THEN 1 END ) as shortLine"), //短线总单量
                               DB::raw("count(CASE WHEN ((end_time-begin_time)/3600)>120 THEN 3 END ) as longLine"), //长线总单量
                               DB::raw("count(CASE WHEN ((end_time-begin_time)/3600) between 49 and 120 THEN 2 END ) as centerLine"), //中线总单量
                              
                               DB::raw("count(CASE WHEN ((end_time-begin_time)/3600)<=48  and final_point > 0 THEN 1 END ) as shortProfitaNum"), //短线盈利单量
                               DB::raw("count(CASE WHEN ((end_time-begin_time)/3600)>120  and final_point > 0 THEN 3 END ) as longProfitNum"),  //长线盈利单量
                               DB::raw("count(CASE WHEN ((end_time-begin_time)/3600) between 49 and 120 and final_point > 0 THEN 2 END ) as centerProfitNum"),//中线盈利单量
                              
                               DB::raw("SUM(CASE WHEN ((end_time-begin_time)/3600)<=48 and final_point<0 THEN final_point+5 END ) as allShortLineLossPoint"), //短线亏损总点数
                               DB::raw("SUM(CASE WHEN ((end_time-begin_time)/3600)<=48 and final_point>0 THEN final_point+5 END ) as allShortLineProfitPoint"), //短线盈利总点数
                               DB::raw("SUM(CASE WHEN (((end_time-begin_time)/3600) between 49 and 120) and final_point<0 THEN final_point+5 END ) as allCenterLineLossPoint"),
                               DB::raw("SUM(CASE WHEN (((end_time-begin_time)/3600) between 49 and 120) and final_point>0 THEN final_point+5 END ) as allCenterLineProfitPoint"),
                               DB::raw("SUM(CASE WHEN ((end_time-begin_time)/3600)>120 and final_point<0 THEN final_point+5 END ) as allLongLineLossPoint"),
                               DB::raw("SUM(CASE WHEN ((end_time-begin_time)/3600)>120 and final_point>0 THEN final_point+5 END ) as allLongLineProfitPoint"))
                      ->where([['tel','=',$tel],['isstop','=',0],['ispersonal','=',0]])
                      ->first();
        $LineAndPoint =   json_encode($LineAndPoint);
        return $LineAndPoint;
    }
    
    
    //总交易，做多交易和做空交易
    function allTrade($tel){
        $all = DB::table('waihui_order')
                    ->select(
//                             DB::raw('sum(CASE WHEN final_point>0 THEN final_point END) as allProfitPoint'),//总盈利点数(只查询盈利的)
                             DB::raw('ROUND(sum(CASE WHEN final_point>0 and buy_status="0" THEN (final_point+5) END),2) as allBuyProfitPoint'),//做多交易总盈利点数(只查询盈利的)
                             DB::raw('ROUND(sum(CASE WHEN final_point>0 and buy_status="1" THEN (final_point+5) END),2) as allSellProfitPoint'),//做空交易总盈利点数(只查询盈利的)
                             DB::raw('ROUND(sum(CASE WHEN final_point>0 THEN (final_point+5) END)/count(CASE WHEN final_point>0 THEN 1 END),2) as avaProfit'),//单均盈利
                             DB::raw('ROUND(sum(CASE WHEN final_point<=0 THEN (final_point+5) END)/count(CASE WHEN final_point<=0 THEN 1 END),2) as avaLoss'),//单均亏损
                             DB::raw('count(CASE WHEN final_point > 0 THEN 1 END) as profitTradeNum'),//盈利交易总单量
                             DB::raw('count(CASE WHEN final_point <=0 THEN 1 END) as lossTradeNum'), //亏损交易总单量
                             DB::raw('ROUND((sum(end_time-begin_time)/count(id))/3600,2) as avgChiCangTime'),//平均持仓时间
                             DB::raw('ROUND(count(CASE WHEN final_point>0 THEN 1 END)/count(id),2)*100 as shenglv'),//胜率
                             DB::raw('ROUND((sum(final_point)+count(id)*5),2) as allPoint')//总盈利点位
                            )
                    ->where([['tel','=',"$tel"],['isstop','=','0'],['ispersonal','=',0]])
                    ->first();

        return $all;
    } 
    
    //最大连胜，最大连亏,最大涨幅，最大回撤
    public  static function maxDada($tel){
        $data['liansheng'] = 0;
        $data['liankui']   = 0;
        $data['zhangfu']   = 0;
        $data['huiche']    = 0;
        
        $arr_zhangfu = array(0); //涨幅
        $arr_huiche  = array(0); //回撤
        $arrb        = array(0); //连败
        $arrs        = array(0); //连胜
        $result = DB::table('waihui_order')
                  ->select('trade_status','final_point')
                  ->where([['tel','=',"$tel"],['isstop','=','0'],['ispersonal','=',0]])
                  ->orderBy('end_time','asc')
//                  ->limit(2)
                  ->get()->toArray();
        if(!$result){
            return $data;
        }
        
        foreach($result as $k=>$v){
            if($v->trade_status == 2){
                $result[$k]->trade_status = 0;
            }
        }
        //dd($result);
        
        if(count($result) == 1){ //当用户只有一个平仓的单子
            if($result[0]->trade_status == 0){
                $data['liankui'] = 1;
                $data['liansheng'] = 0;
                $data['zhangfu'] = ($result[0]->final_point+5);
            }else{
                $data['liankui'] = 0;
                $data['liansheng'] = 1;
                $data['zhangfu'] = ($result[0]->final_point+5);
            }
        }else{
            $ls = 1; //连胜
            $lb = 1; //连败
            $huiche  = 0; //回撤
            $zhangfu = 0; //涨幅

            for($i=0,$t = count($result)-1;$i < $t;$i++) {
//                if($result[$i]->trade_status == 0){
                  if($result[$i]->final_point+5 <= 0){
//                    if($result[$i]->trade_status == $result[$i+1]->trade_status){
                    if((($result[$i]->final_point+5 <= 0) && ($result[$i+1]->final_point+5 <= 0)) || (($result[$i]->final_point+5 > 0) && ($result[$i+1]->final_point+5 > 0))){
                        if($i+1 == count($result)-1){
                            $arrb[] = $lb+1;
                            $arr_huiche[] = $huiche + ($result[$i]->final_point+5) + ($result[$i+1]->final_point+5);
                        }else{
                            $lb++;
                            $huiche = $huiche  + ($result[$i]->final_point+5);
                        }

                    }else{
                        $arrb[] = $lb;  //连败
                        $arr_huiche[] = $huiche + ($result[$i]->final_point+5);  //回撤
                        $lb = 1;
                        $huiche  = 0;
                        continue;
                    }
//                }else if($result[$i]->trade_status == 1) {
                  }else if($result[$i]->final_point+5 > 0){
//                    if($result[$i]->trade_status == $result[$i+1]->trade_status){
                      if((($result[$i]->final_point+5 <= 0) && ($result[$i+1]->final_point+5 <= 0)) || (($result[$i]->final_point+5 > 0) && ($result[$i+1]->final_point+5 > 0))){
                        if($i+1 == count($result)-1){
                            $arrs[] = $ls+1;  //连胜
                            $arr_zhangfu[] = $zhangfu + ($result[$i]->final_point+5) + ($result[$i+1]->final_point+5);
                        }else{
                            $ls++;
                            $zhangfu = $zhangfu + ($result[$i]->final_point+5);
                        }

                    }else{
                        $arrs[] = $ls;  //连胜
                        $arr_zhangfu[] = $zhangfu + ($result[$i]->final_point+5); //涨幅
                        $ls = 1;
                        $zhangfu = 0;
                        continue;
                    }
                }
            }

            rsort($arrs,SORT_NUMERIC );
            rsort($arrb,SORT_NUMERIC );
            sort($arr_huiche,SORT_NUMERIC ); //最大回撤按照从小到大排序
            rsort($arr_zhangfu,SORT_NUMERIC );

            $data['liansheng'] = $arrs[0];
            $data['liankui']   = $arrb[0];
            $data['huiche'] = $arr_huiche[0];
            $data['zhangfu']   = $arr_zhangfu[0];
        }
       // dd($data);
        return $data;
    }

    //稳定值,查询最近两周的
    public static function wenDindZhi($tel){
        $return['wending'] = 0;
        $return['fengXianBi'] = '0:0';
        $now = time();
        $begin_time = $now-13*86400;
        //dd($begin_time);
        $data = DB::table('waihui_order')
                ->select('final_point')
                ->where([['tel','=',"$tel"],['isstop','=','0'],['ispersonal','=',0]])
                ->pluck('final_point');
        if(!$data){
            return $return;
        }
        
        $yingli = 0;
        $kuisun = 0;
        $i = 0; //盈利单量
        $j = 0; //亏损单量
        foreach($data as $key => $val){
            if($val > 0){
                $i++;
                $yingli = $yingli + $val;
            }else{
                $j++;
                $kuisun = $kuisun + $val;
            }
        }
        //dd($i,$j,$yingli,$kuisun);
        if(($j) != 0){
            $return['fengXianBi'] = round((($yingli / ($i?$i:1))/(-$kuisun / $j)),2).' : 1';
        }else{
            $return['fengXianBi'] = '暂无风险';
        }
       
        if(-$kuisun + $yingli != 0){
            $return['wenDing'] = round(($yingli / (-$kuisun + $yingli)*10),2);
        }else{
            $return['wenDing'] = 0;
        }
       //dd($return);
        return $return;
    }
    
   
    //周收益
    public function ajaxOrderWeek(Request $request){
        $id       = intval(trim($request->analyst_id));
        $id       = $id ? $id:$request->session()->get('eai')['id'];
        $tel      = DB::table('waihui_member')->where(array('id'=>$id))->value('tel');
        $pagesize = 8; //每页显示数量
        $page     = intval(trim($request->page)) ? intval(trim($request->page)) :1; //页码
        $offset   = ($page-1)*$pagesize; //偏移量
        $where['o.tel']          = $tel;
        $where['o.ispersonal']  = 0;
        $where['o.isstop']       = 0;
        $totalnum  = DB::table('waihui_order as o')->select(DB::raw("FROM_UNIXTIME(o.end_time, '%Y%u') AS days"))->where($where)->groupBy('days')->get()->toArray();
        $totalnum  = count($totalnum); //总条数
        $totalpage = ceil($totalnum/$pagesize);//总页数
        $weekOrder = DB::table('waihui_order as o')->select(DB::raw("FROM_UNIXTIME(o.end_time, '%Y%u') AS days"),DB::raw("ROUND((SUM(o.final_point)+COUNT(o.id)*5),2) as final_point"),DB::raw("COUNT(o.id) as num"))->where($where)->groupBy('days')->orderBy('days','asc')->offset($offset)->limit($pagesize)->get()->toArray();
        $allFinalPoint = 0; //总计点位
        $allOrderNum   = 0; //总计收益比例
        $allScale      = 0; //总计喊单量
        if($weekOrder){
            foreach ($weekOrder as $k=>$v){
                if($page == 1 && $k == 0){
                    //第一页 第一周
                    $weekOrder[$k]->scale = round((($weekOrder[$k]->final_point-0)/1),2)*100; //收益比例
                }elseif($page != 1 && $k == 0){
                    $preFinalPoint   = round(trim($request->finalpoint),2);//上一页 最后一周  总收益
                    $weekOrder[$k]->scale = round((($weekOrder[$k]->final_point-$preFinalPoint)/($preFinalPoint == 0?1:abs($preFinalPoint))),2)*100; //收益比例
                }else{
                    $preFinalPoint = $weekOrder[$k-1]->final_point;
                    $weekOrder[$k]->scale = round((($weekOrder[$k]->final_point-$preFinalPoint)/($preFinalPoint == 0?1:abs($preFinalPoint))),2)*100; //收益比例
                }
                $allFinalPoint      = DB::table('waihui_order as o')->select(DB::raw("ROUND((SUM(final_point)+COUNT(o.id)*5),2) as final_point"))->where($where)->get()->toArray();
                $allFinalPoint      = $allFinalPoint[0]->final_point?$allFinalPoint[0]->final_point:0;
                $allOrderNum        = DB::table('waihui_order as o')->select(DB::raw("COUNT(id) as ordernum"))->where($where)->get()->toArray();
                $allOrderNum        = $allOrderNum[0]->ordernum?$allOrderNum[0]->ordernum:0;
                $allScale           = $allFinalPoint;
            }

        }
        return json_encode(array('orderdata'=>$weekOrder,'totalpage'=>$totalpage,'allFinalPoint'=>$allFinalPoint,'allOrderNum'=>$allOrderNum,'allScale'=>$allScale,'page'=>$page));
    }

    //盈亏图
    public function profitLoss($tel){
        $time   = '';
        $end_point_str    = '';
        $profit_point_str = '';
        $loss_point_str   = '';
        $whe['o.tel'] = $tel;
        $whe['o.isstop'] = 0;
        $whe['o.ispersonal'] = 0;
        $result  = DB::table('waihui_order as o')->select('tradeid','begin_point','end_point','profit_point','loss_point','target_profit_point','target_loss_point','final_point',"begin_time","end_time",DB::raw("FROM_UNIXTIME(end_time, '%Y-%m-%d日') as datetime"))->where($whe)->orderBy('o.end_time','desc')->limit(10)->get()->toArray();
        $result = array_reverse($result);
        foreach ($result as $k=>$v){
            $str = '';
            if($k < count($result)-1){
                $str = ',';
            }
            $time .= date('Y-m-d',$v->end_time).$str;
            $end_point_str .= ($v->final_point+5).$str;
            $profit_point_str .= $v->profit_point.$str;
            $loss_point_str .= -$v->loss_point.$str;
        }
        return array($time,$end_point_str,$profit_point_str,$loss_point_str);
    }
    //分析师K线图
    public function allPoint($tel){
        $where['o.ispersonal']  = 0; //网站下单的
        $where['o.isstop']      = 0; //已平仓的
        $where['o.tel']         = $tel;
        $result = DB::table('waihui_order as o')->select("o.final_point","o.end_time",DB::raw("FROM_UNIXTIME(o.end_time, '%Y-%m-%d') as datetime"))->where([['o.final_point','!=' ,null]])->where($where)->orderBy('datetime','asc')->get()->toArray();
        $str       = '';
        if($result){
            $total     = 0;
            $timeDay   = [];    //时间
            $pointarr  = [];   //存放 每天 最高、最低、开始、结束
            $daypoint  = [];  //当天数据
            $prepoint  = [];   //存放昨天的数据
            $i         = 0;    //每天的单量
            $num       = 0;    //总单量
            foreach($result as $k=>$v){
                if($k <= count($result)-1){
                    $total = $total + $result[$k]->final_point+5; //每天每单相加后的值
                    $daypoint[] = round($total,2); //将值放入数组中 以便获取 最大值最小值
                    $i ++ ; //每天的单量
                    //条件是否正确
                    if($k == count($result)-1){ //最后一天数据
                        $istrue = true;
                    }else{
                        $istrue = $result[$k]->datetime != $result[$k+1]->datetime ?true:false; //当前日期不等于下一个日期，则当前日期结束
                    }
                    if($istrue){ //当前一天的结束
                        $str .= $result[$k]->datetime.','; //拼接时间
//                        $pointarr[$result[$k]->datetime] = [];

                        //第一天和以后每天的区别
                        if($timeDay){
//                            array_push($pointarr[$result[$k]->datetime],$prepoint[count($prepoint)-1]); //开始值为前一天的结束值
                            $str .= round($prepoint[count($prepoint)-1],2).','.round($daypoint[count($daypoint)-1],2).','; //拼接开始值、结束值
                        }else{
//                            array_push($pointarr[$result[$k]->datetime],0); //第一天开始值 为0
                            $str .= '0,'.round($daypoint[count($daypoint)-1],2).','; //拼接开始值、结束值
                        }
//                        array_push($pointarr[$result[$k]->datetime],$daypoint[count($daypoint)-1]); //结束值
                        //单均盈利
                        $num += $i;
                        $singlepoint = round($daypoint[count($daypoint)-1]/$num,2);

                        $prepoint  = $daypoint; //将数据存起来

                        sort($daypoint); //对数组进行从小到大排序
//                        array_push($pointarr[$result[$k]->datetime],$daypoint[0]); //一天中最小值
//                        array_push($pointarr[$result[$k]->datetime],$daypoint[count($daypoint)-1]); //一天中最大值
//                        array_push($pointarr[$result[$k]->datetime],$i); //单量

                        $str .= round($daypoint[0],2).','.round($daypoint[count($daypoint)-1],2).','.$i.",0"; //拼接最小值、最大值、单量
                        $str .= ",".$singlepoint.";";

//                        array_push($pointarr[$result[$k]->datetime],$singlepoint); //单均盈利

                        $timeDay[] = $result[$k]->datetime; //时间数组
                        $daypoint  = []; //新的一天重置数组
                        $i         = 0;
                    }
                }
            }
        }
        return $str;
    }
    
    function timeDistribution($tel){ //时间分布，亚盘、欧盘、美盘   
        $return['yapan'] = 0 ;
        $return['opan'] = 0 ;
        $return['meipan'] = 0 ;
        
        $data = DB::table('waihui_order')
                ->select('begin_time') 
                ->where([['tel','=',"$tel"],['isstop','=','0'],['ispersonal','=',0]])
                ->pluck('begin_time');
        if(!$data){
            return $return;
        }
        
        foreach($data as $k=>$v){
            $data[$k]= intval(date('Gis',$v));
            if($data[$k] >= 50000 && $data[$k] <= 135959){
                $return['yapan']++;
            }else if($data[$k] >= 140000 && $data[$k] <= 195959){
                $return['opan']++;
            }else if($data[$k] >= 200000 && $data[$k] <= 235959){
                $return['meipan']++;
            }else if($data[$k] >=0 && $data[$k] <= 45959){
                $return['meipan']++;
            }
        }
        //dd($return);
        return $return;
      
    }
    //交易时间分布
    public function delTimeMap($tel){
        $where['o.tel']          = $tel;
        $where['o.ispersonal']  = 0;
        $where['o.isstop']       = 0;
        $weekOrder = DB::table('waihui_order as o')->select(DB::raw("count(id) AS final_point"),DB::raw("ROUND(((count(case when trade_status='1' then 1 end) / count(tel))*100),2) AS winrate"),DB::raw("CASE WHEN 00< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=02 THEN '00:00-02:00' WHEN 02< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=04 THEN '02:00-04:00' WHEN 04< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=06 THEN '04:00-06:00' WHEN 06< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=08 THEN '06:00-08:00' WHEN 08< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=10 THEN '08:00-10:00' WHEN 10< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=12 THEN '10:00-12:00' WHEN 12< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=14 THEN '12:00-14:00' WHEN 14< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=16 THEN '14:00-16:00' WHEN 16< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=18 THEN '16:00-18:00' WHEN 18< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=20 THEN '18:00-20:00' WHEN 20< FROM_UNIXTIME(o.begin_time, '%H') && FROM_UNIXTIME(o.begin_time, '%H') <=22 THEN '20:00-22:00' ELSE '22:00-24:00' END  AS hours"))->where($where)->groupBy('hours')->orderBy('hours','asc')->get()->toArray();
        $finalpointstr = '';
        $timestr       = '';
        $winratestr    = '';
        if($weekOrder){
            foreach ($weekOrder as $k=>$v){
                if($k < count($weekOrder)-1){
                    $str = ",";
                }else{
                    $str = "";
                }
                $finalpointstr .= $v->final_point.$str;
                $timestr       .= $v->hours.$str;
                $winratestr    .= $v->winrate.$str;
            }
        }
        return array($finalpointstr,$timestr,$winratestr);

    }
    
    //点位区间图
    function pointBetweenChat($tel){
        $data = DB::table('waihui_order')
                ->select(
                        DB::raw('count(CASE when ROUND((final_point+5),0) between 0 and 10 then 1 END)as znum1'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -10 and 0 then 1 END)as fnum1'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) between 11 and 20 then 1 END)as znum2'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -20 and -11 then 1 END)as fnum2'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) between 21 and 30 then 1 END)as znum3'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -30 and -21 then 1 END)as fnum3'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) between 31 and 40 then 1 END)as znum4'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -40 and -31 then 1 END)as fnum4'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) between 41 and 50 then 1 END)as znum5'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -50 and -41 then 1 END)as fnum5'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) between 51 and 60 then 1 END)as znum6'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -60 and -51 then 1 END)as fnum6'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) between 61 and 70 then 1 END)as znum7'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -70 and -61 then 1 END)as fnum7'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) between 71 and 80 then 1 END)as znum8'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -80 and -71 then 1 END)as fnum8'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) between 81 and 90 then 1 END)as znum9'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -90 and -81 then 1 END)as fnum9'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) between 91 and 100 then 1 END)as znum10'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) between -100 and -91 then 1 END)as fnum10'),

                        DB::raw('count(CASE when ROUND((final_point+5),0) > 100 then 1 END)as znum11'),
                        DB::raw('count(CASE when ROUND((final_point+5),0) < -100 then 1 END)as fnum11')
                        
                        )
                ->where([['tel','=',"$tel"],['isstop','=','0'],['ispersonal','=',0]])
                ->get()->toArray();
        
        if($data){
            for($i = 1;$i <= 11; $i++){
                $a = 'znum'.$i; //盈利单
                $b = 'fnum'.$i; //亏损单
                $yingLiNum[] = $data[0]->$a; //盈利单量
                $kuiSunNum[] = $data[0]->$b; //盈利单量
                if($data[0]->$b == 0 || $data[0]->$b == ''){
                    $yingKuiBi[] = $data[0]->$a;
                }else{
                    $yingKuiBi[] = round(($data[0]->$a/$data[0]->$b),2);
                }
            }
            $yingLiNumStr = implode(',',$yingLiNum);
            $kuiSunNumStr = implode(',',$kuiSunNum);
            $yingKuiBiStr = implode(',',$yingKuiBi);
        }else{
            $yingLiNumStr = '';
            $kuiSunNumStr = '';
            $yingKuiBiStr = '';
        }
             
        $return = array($yingLiNumStr,$kuiSunNumStr,$yingKuiBiStr);
        return $return;
    }
    
    
    function genSuiInfo($tel){
        $data = DB::table('waihui_gendan')
                ->select(
                        DB::raw('round(sum(profit)/count(id),2) as avgProfit'), //单均收益
                        DB::raw('round(sum(profit),2) as allProfit') //订阅总收益
                        )
                ->where([['follower_tel','=',$tel],['isstop','=',0]])
                ->get();
        //dd($data);
        return $data;
    }
    
     //总盈利交易
    function allMyProfitTrade($tel){
        $allProfitTrade = DB::table('waihui_order')  
                        ->select(DB::raw('count(*) as num'))
                        ->where([['tel','=',"$tel"],['final_point','>=','0']])
                        ->pluck('num');
        $allProfitTrade = $allProfitTrade[0] ? $allProfitTrade[0] : 0;
        return $allProfitTrade;
    }
}
